<template>
  <div class="coupons-container">
    <!-- 标题和操作按钮 -->
    <div class="header">
      <div class="title">
        <el-icon><Ticket /></el-icon>
        <h2>礼券管理</h2>
      </div>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增礼券
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <div class="left-section">
          <el-form-item label="礼券名称">
            <el-input
                v-model="searchForm.name"
                placeholder="请输入礼券名称"
                clearable
                prefix-icon="Ticket"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
                v-model="searchForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 160px"
            >
              <el-option label="已发布" value="1" />
              <el-option label="未发布" value="0" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
        </div>
        <div class="right-section">
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="name" label="礼券名称" />
        <el-table-column prop="type" label="类型">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.type)">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="面值">
          <template #default="scope">
            {{ formatValue(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="validFrom" label="有效期开始时间" />
        <el-table-column prop="validUntil" label="有效期结束时间" />
        <el-table-column prop="usageConditions" label="适用用范围" />
        <el-table-column prop="applicableScope" label="使用条件" />
        <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === '已发布' ? 'success' : 'info'">
            {{ row.status }}
          </el-tag>
        </template>
        </el-table-column>
        <el-table-column label="操作" width="350" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              <el-icon><View /></el-icon>查看
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>修改
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
            <el-button
                v-if="row.status === '未发布'"
                type="success"
                link
                @click="handlePublish(row)"
            >
              <el-icon><Upload /></el-icon>发布
            </el-button>
            <el-button
                v-if="row.status === '已发布'"
                type="warning"
                link
                @click="handleUnpublish(row)"
            >
              <el-icon><Switch /></el-icon>取消发布
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 20, 50]"
          :page-size="size"
          layout="total, sizes, prev, pager, next"
          :total="total"
      />
    </div>

    <!-- 弹窗 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          :disabled="dialogType === 'view'"
      >
        <el-form-item label="礼券名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="折扣券" value="折扣券" />
            <el-option label="现金券" value="现金券" />
            <el-option label="满减券" value="满减券" />
          </el-select>
        </el-form-item>

        <!-- 根据券类型显示不同的输入字段 -->
        <template v-if="form.type === '折扣券'">
          <el-form-item label="折扣率" prop="discount">
            <el-input-number
                v-model="form.discount"
                :min="0"
                :max="10"
                :precision="1"
                :step="0.1"
            />
            <span class="ml-2">折</span>
          </el-form-item>
        </template>

        <template v-else-if="form.type === '现金券'">
          <el-form-item label="金额" prop="amount">
            <el-input-number
                v-model="form.amount"
                :min="0"
                :precision="2"
            />
            <span class="ml-2">元</span>
          </el-form-item>
        </template>

        <template v-else-if="form.type === '满减券'">
          <el-form-item label="满足金额" prop="fullAmount">
            <el-input-number
                v-model="form.fullAmount"
                :min="0"
                :precision="2"
            />
            <span class="ml-2">元</span>
          </el-form-item>
          <el-form-item label="减免金额" prop="reduceAmount">
            <el-input-number
                v-model="form.reduceAmount"
                :min="0"
                :precision="2"
            />
            <span class="ml-2">元</span>
          </el-form-item>
        </template>

        <el-form-item label="有效期" prop="validDates">
          <el-date-picker
              v-model="form.validDates"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 1, 1, 23, 59, 59)
              ]"
          />
        </el-form-item>

        <el-form-item label="使用条件" prop="usageConditions">
          <el-input
              v-model="form.usageConditions"
              type="textarea"
              :rows="3"
              placeholder="请输入使用条件"
          />
        </el-form-item>

        <el-form-item label="适用范围" prop="applicableScope">
          <el-select
              v-model="form.applicableScope"
              multiple
              filterable
              placeholder="请选择适用站点"
              style="width: 100%"
          >
            <el-option
                v-for="station in stationOptions"
                :key="station.id"
                :label="station.stationName"
                :value="station.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ station.stationName }}</span>
                <span style="color: #8492a6; font-size: 13px">
                  {{ station.stationType ? `(${station.stationType})` : '' }}
                </span>
              </div>
              <div style="font-size: 12px; color: #909399">
                {{ station.address }}
              </div>
            </el-option>
          </el-select>
        </el-form-item>1
        <el-form-item label="状态">
          <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 160px"
          >
            <el-option label="已发布" value="已发布" />
            <el-option label="未发布" value="未发布" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" v-if="dialogType !== 'view'">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {
  Plus,
  Search,
  Refresh,
  Ticket,
  View,
  Edit,
  Delete,
  CircleClose,
  Check
} from '@element-plus/icons-vue'

// 状态常量
const STATUS = {
  PUBLISHED: '发布',    // 修改为中文状态
  UNPUBLISHED: '未发布'   // 修改为中文状态
}


// 响应式数据
const searchForm = reactive({
  name: '',
  status: ''
})


// 表单数据
const form = ref({
  name: '',
  type: '',
  discount: 0,
  amount: 0,
  fullAmount: 0,
  reduceAmount: 0,
  validDates: [],
  status: '0', // 默认未发布
  usageConditions: '',
  applicableScope: []
})

const tableData = ref([])
const page = ref(1)
const size = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const stationOptions = ref([])
// 获取站点列表
const fetchStations = async () => {
  try {
    const res = await axios.get('/station/getStationByPage', {
      params: {
        page: 0,
        size: 1000,
        status: '正常'
      }
    })
    if (res.data && res.data.records) {
      stationOptions.value = res.data.records
    }
  } catch (error) {
    console.error('获取站点列表失败：', error)
    ElMessage.error('获取站点列表失败')
  }
}

// 监听类型变化
watch(
    () => form.value.type,
    (newType, oldType) => {
      if (newType && form.value.name) {
        if (oldType) {
          form.value.name = form.value.name.replace(oldType, newType)
        } else {
          form.value.name = `${form.value.name}${newType}`
        }
      }
    }
)

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入礼券名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  validDates: [{ required: true, message: '请选择有效期', trigger: 'change' }],
  discount: [{ required: true, message: '请输入折扣率', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  fullAmount: [{ required: true, message: '请输入满足金额', trigger: 'blur' }],
  reduceAmount: [{ required: true, message: '请输入减免金额', trigger: 'blur' }],
  usageConditions: [{ required: true, message: '请输入使用条件', trigger: 'blur' }],
  applicableScope: [{ required: true, message: '请选择适用范围', trigger: 'change' }]
}

// 计算属性
const dialogTitle = computed(() => {
  const titles = {
    add: '新增礼券',
    edit: '修改礼券',
    view: '查看礼券'
  }
  return titles[dialogType.value]
})

// 获取标签类型
const getTagType = (type) => {
  const typeMap = {
    '折扣券': 'success',
    '现金券': 'warning',
    '满减券': 'info'
  }
  return typeMap[type] || 'default'
}

// 格式化显示值
const formatValue = (row) => {
  switch (row.type) {
    case '折扣券':
      return `${row.value}折`
    case '现金券':
      return `¥${row.value}`
    case '满减券':
      return `满${row.fullAmount}减${row.value}`
    default:
      return row.value
  }
}

// 格式化提交值
const formatSubmitValue = (formData) => {
  switch (formData.type) {
    case '折扣券':
      return formData.discount
    case '现金券':
      return formData.amount
    case '满减券':
      return formData.reduceAmount
    default:
      return 0
  }
}

// 获取数据
const fetchData = async () => {
  try {
    const res = await axios.get('/coupons/getCouponsByPage', {
      params: {
        page: page.value,
        size: size.value,
        name: searchForm.name || undefined,
        status: searchForm.status || undefined
      }
    })
    if (res.data) {
      tableData.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取数据失败：', error)
    ElMessage.error('获取数据失败')
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.status = ''
  handleSearch()
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchData()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    id: null,
    name: '',
    type: '',
    discount: 0,
    amount: 0,
    fullAmount: 0,
    reduceAmount: 0,
    validDates: [],
    status: '未发布',  // 默认未发布
    usageConditions: '',
    applicableScope: []
  }
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  dialogType.value = 'view'
  form.value = {
    ...row,
    validDates: [row.validFrom, row.validUntil],
    discount: row.type === '折扣券' ? parseFloat(row.value) : 0,
    amount: row.type === '现金券' ? parseFloat(row.value) : 0,
    reduceAmount: row.type === '满减券' ? parseFloat(row.value) : 0,
    fullAmount: row.type === '满减券' ? parseFloat(row.fullAmount) : 0,
    usageConditions: row.usageConditions,
    applicableScope: row.applicableScope ? row.applicableScope.split(',').map(Number) : []
  }
  dialogVisible.value = true
}

// 修改
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = {
    id: row.id,
    name: row.name,
    type: row.type,
    validDates: [row.validFrom, row.validUntil],
    status: row.status,
    discount: row.type === '折扣券' ? parseFloat(row.value) : 0,
    amount: row.type === '现金券' ? parseFloat(row.value) : 0,
    reduceAmount: row.type === '满减券' ? parseFloat(row.value) : 0,
    fullAmount: row.type === '满减券' ? parseFloat(row.fullAmount) : 0,
    usageConditions: row.usageConditions,
    applicableScope: row.applicableScope ? row.applicableScope.split(',').map(Number) : []
  }
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该礼券?', '提示')
    const res = await axios.delete(`/coupons/deleteCoupons?id=${row.id}`)
    if (res.data === '删除成功') {
      ElMessage.success('删除成功')
      fetchData()
    }
  } catch (error) {
    console.error('删除失败：', error)
    ElMessage.error('删除失败')
  }
}

// 取消发布
const handleUnpublish = (row) => {
  ElMessageBox.confirm('确认取消发布该礼券?', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await axios.put('/coupons/updateCoupons', {
        ...row,
        status: '未发布'
      })
      ElMessage.success('取消发布成功')
      fetchData()
    } catch (error) {
      ElMessage.error('取消发布失败')
    }
  })
}

// 发布
const handlePublish = (row) => {
  ElMessageBox.confirm('确认发布该礼券?', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await axios.put('/coupons/updateCoupons', {
        ...row,
        status: '已发布'
      })
      ElMessage.success('发布成功')
      fetchData()
    } catch (error) {
      ElMessage.error('发布失败')
    }
  })
}


// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    const submitData = {
      id: form.value.id,
      name: form.value.name,
      type: form.value.type,
      value: formatSubmitValue(form.value),
      validFrom: form.value.validDates?.[0],
      validUntil: form.value.validDates?.[1],
      status: form.value.status,
      usageConditions: form.value.usageConditions,
      applicableScope: form.value.applicableScope.join(',')
    }

    if (form.value.type === '满减券') {
      submitData.fullAmount = form.value.fullAmount
    }

    if (dialogType.value === 'add') {
      const res = await axios.post('/coupons/addCoupons', submitData)
      if (res.data === true) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        fetchData()
      }
    } else {
      const res = await axios.put('/coupons/updateCoupons', submitData)
      if (res.data === '更新成功') {
        ElMessage.success('修改成功')
        dialogVisible.value = false
        fetchData()
      }
    }
  } catch (error) {
    console.error('提交失败：', error)
    ElMessage.error('提交失败：' + (error.response?.data?.message || error.message))
  }
}

// 分页
const handleSizeChange = (val) => {
  size.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  page.value = val
  fetchData()
}

// 生命周期钩子
onMounted(() => {
  fetchData()
  fetchStations()
})
</script>

<style scoped>
.coupons-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 48px);
}

.header {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.header .title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header .title h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.search-container {
  margin-bottom: 24px;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.right-section {
  margin-left: auto;
}

.table-container {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.pagination-container {
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;
}

.ml-2 {
  margin-left: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}

:deep(.el-input) {
  width: 100%;
}

@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .left-section {
    width: 100%;
  }

  .right-section {
    margin-left: 0;
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  :deep(.el-form-item) {
    width: 100%;
  }

  :deep(.el-input) {
    width: 100%;
  }
}
</style>